package xing.design.pattern.behavioral.Memento.sample3_andCommandPattern.editor;

import xing.design.pattern.behavioral.Memento.sample3_andCommandPattern.editor.command.edit.AddStringCommand;
import xing.design.pattern.behavioral.Memento.sample3_andCommandPattern.editor.command.ICommand;
import xing.design.pattern.behavioral.Memento.sample3_andCommandPattern.editor.memento.Memento;

/**
 * 简单的编辑器，只保存一个 String，且只有简单的操作。
 *
 * @author xing
 * @date 2023/2/10 14:58:08
 */
public class Editor {
    private String content ;
    private final History history;
    private final String INIT_CONTENT = "";
    // private final EditorMemento INIT_MEMENTO = new EditorMemento(INIT_CONTENT);

    public Editor() {
        this.clear();
        history = new History(this);
    }

    public Editor(String content) {
        this();
        this.execute(new AddStringCommand(content));
    }

    public void execute(ICommand c) {
        c.execute(this);
    }

    public History getHistory() {
        return history;
    }

    public void clear() {
        this.content = INIT_CONTENT;
        // INIT_MEMENTO.restore();
    }

    public Memento createMemento() {
        return new EditorMemento(this.content);
    }

    private class EditorMemento implements Memento {
        private String content;

        private EditorMemento(String content) {
            this.content = content;
        }

        @Override
        public void restore() {
            Editor.this.content = this.content;
        }


        @Override
        public String getContent() {
            return this.content;
        }
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
